package com.example.elasticsearchhepler.strategy.aggregation;

import com.example.elasticsearchhepler.entity.common.AggregationParamEntity;
import com.example.elasticsearchhepler.exception.BizException;
import com.example.elasticsearchhepler.utils.EmptyUtil;
import com.example.elasticsearchhepler.utils.SpringContextUtil;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.springframework.stereotype.Service;

@Service(value = "dateRangeParseAggregation")
public class DateRangeParseAggregationServiceImpl implements ParseAggregationService {
    @Override
    public AggregationBuilder parseAggregation(AggregationParamEntity param) throws BizException {
        AggregationBuilder aggregationBuilder = AggregationBuilders.dateRange(param.getName()).field(param.getField());
        if (EmptyUtil.isEmpty(param.getSubAgg())){
            return aggregationBuilder;
        }
        for (AggregationParamEntity e:param.getSubAgg()) {
            ParseAggregationService service = (ParseAggregationService) SpringContextUtil.getBean(e.getType().toString()+"ParseAggregation");
            aggregationBuilder.subAggregation(service.parseAggregation(e));
        }
        return aggregationBuilder;
    }
}
